source('base.R')

hist_breaks = 200

particial <- function(log, profile, output=NULL) {
    p_ratio <- pos_action_ratio(log)
    log$p_ratio <- p_ratio[as.character(log$user_id)]

    positive_user <- log[log$p_ratio<=0.1,]
    negative_user <- log[log$p_ratio>=0.9,]

    overall(positive_user, profile, output)
    overall(negative_user, profile, output)
}

overall <- function(log, profile, output=NULL) {
    user_data <- data.frame(user_id=as.integer(levels(factor(log$user_id))))

    count <- table(log$user_id)
    user_data$count <- count[as.character(user_data$user_id)]

    user_data$dur <- duration(log)
    ifelse('p_ratio' %in% colnames(log), user_data$p_ratio <- log$p_ratio[match(user_data$user_id, log$user_id)], user_data$p_ratio <- pos_action_ratio(log))

    user_data$ban <- profile$ban[match(user_data$user_id, profile$user_id)]
    user_data$heart <- profile$heart[match(user_data$user_id, profile$user_id)]
    user_data$play <- profile$play[match(user_data$user_id, profile$user_id)]
    user_data$artist <- profile$artist[match(user_data$user_id, profile$user_id)]

    user_data <- user_data[complete.cases(user_data),]

    hist(user_data$count, breaks=hist_breaks)
    hist(user_data$count[user_data$count<=250], breaks=hist_breaks)
    hist(user_data$dur, breaks=hist_breaks)
    hist(user_data$p_ratio, breaks=hist_breaks)
    hist(user_data$ban, breaks=hist_breaks)
    hist(user_data$ban[user_data$ban<=1000], breaks=hist_breaks)
    hist(user_data$heart, breaks=hist_breaks)
    hist(user_data$heart[user_data$heart<=1500], breaks=hist_breaks)
    hist(user_data$play, breaks=hist_breaks)
    hist(user_data$play[user_data$play<=20000], breaks=hist_breaks)
    hist(user_data$artist, breaks=hist_breaks)
    hist(user_data$artist[user_data$artist<=100], breaks=hist_breaks)

    act_avg <- action_avg(log)
    act_ratio <- action_ratio(log)

    sink(output)
    print(mean(user_data$count))
    print(mean(user_data$dur))
    print(mean(user_data$p_ratio))
    print(mean(user_data$ban))
    print(mean(user_data$heart))
    print(mean(user_data$play))
    print(mean(user_data$artist))
    print(act_avg)
    print(act_ratio)

    user_stats <- user_data[,c('count', 'dur', 'p_ratio', 'ban', 'heart', 'play', 'artist')]
    print(cor_analyse(user_stats))
    print(KLdiv_analyse(user_stats))

    print(seq_mining(log, 'analyse.temp'))
    sink()
}

run <- function(log_filename, profile_filename, output_filename) {
    log <- read(log_filename)
    profile <- read(profile_filename)

    output <- file(output_filename, open='a')

    overall(log, profile, output)
    particial(log, profile, output)
}

run('data/daily_log_2011-04-13', 'data/user_profile_2011-04-14_10', 'analyse.output')
